<script setup>
import { ref, defineEmits, defineProps, watch } from 'vue'
import { ElMessage } from 'element-plus'
import ItemSelectDialog from '@/views/outbound/outboundorder/items.vue'
import { batchSaveApi } from '@/api/outbound/outboundorderdetails'
import { ElIcon } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { addApi } from '@/api/outbound/outboundorder'
// import { batchAddApi } from '@/api/outbound/outboundOrderDetails'

const emit = defineEmits(['refresh'])
const ruleFormRef = ref(null)
const rules = ref({
  customerId: [
    { required: true, message: '请选择客户', trigger: 'blur' }
  ]
})
//细节表的数据
// 添加仓库分配数据存储
const warehouseAllocation = ref({})

// 添加仓库分配对话框引用
const warehouseDialogRef = ref(null)

// 打开仓库分配对话框
const openWarehouseAllocation = () => {
  // 这里需要打开仓库分配对话框，并传递已选商品信息
  // 实现方式取决于你的仓库分配组件设计
}

// 处理仓库分配完成
const handleWarehouseAllocation = (allocationData) => {
  // 保存仓库分配数据
  warehouseAllocation.value = allocationData
  // 继续提交流程
  confirmWithWarehouseData()
}

const dialogVisible = ref(false)
const dialogFormData = ref({
  id: null,
  customerId: null,
  invoiceCode: '',
  status: 1,
  totalCount: 0,
  totalWeight: 0,
  totalVolume: 0,
  empId: 0,
  price: 0,
  logisticsCompanyId: null,
  logisticsNumber: '',
  saasId: null,
  createTime: null,
  createBy: '',
  updateTime: null,
  updateBy: '',
  isDel: 1
})

// 已选商品列表：每项包含商品信息和数量
const selectedItems = ref([])

const showItemSelect = ref(false)

// 添加商品（从弹窗选择）
const addItem = (item) => {
  if (!selectedItems.value.some(i => i.skuId === item.id)) {
    selectedItems.value.push({
      skuId: item.id,
      title: item.title,
      code: item.code,
      commodityCode: item.commodityCode,
      supplierName: item.supplierName,
      brandName: item.brandName,
      price: item.price,
      weight: item.weight || 0,   // 添加重量信息
      volume: item.volume || 0,   // 添加体积信息
      count: 1 // 默认数量为1
    })
    calculateTotals() // 更新总计
  }
}
// 计算总计信息
const calculateTotals = () => {
  let totalCount = 0
  let totalWeight = 0
  let totalVolume = 0

  selectedItems.value.forEach(item => {
    totalCount += item.count || 0
    // 根据商品数据中的weight和volume计算总重量和总体积
    totalWeight += (item.weight || 0) * (item.count || 0)
    totalVolume += (item.volume || 0) * (item.count || 0)
  })

  dialogFormData.value.totalCount = totalCount
  dialogFormData.value.totalWeight = totalWeight
  dialogFormData.value.totalVolume = totalVolume
}
// 删除商品
const removeItem = (index) => {
  selectedItems.value.splice(index, 1)
  calculateTotals() // 更新总计
}

// 修改数量
const changeCount = (index, value) => {
  if (value < 0) return
  selectedItems.value[index].count = value
  calculateTotals() // 更新总计
}

const props = defineProps({
  customerList: {
    default: () => []
  }
})
watch(selectedItems, () => {
  calculateTotals()
}, { deep: true })
const resetForm = () => {
  dialogVisible.value = false
  dialogFormData.value = {
    id: null,
    customerId: null,
    invoiceCode: '',
    status: 1,
    totalCount: 0,
    totalWeight: 0,
    totalVolume: 0,
    empId: 0,
    price: 0,
    logisticsCompanyId: null,
    logisticsNumber: '',
    saasId: null,
    createTime: null,
    createBy: '',
    updateTime: null,
    updateBy: '',
    isDel: 1
  }
  selectedItems.value = []
  ruleFormRef.value?.resetFields()
}

const confirm = async () => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 首先保存出库单主表
        const res = await addApi(dialogFormData.value)
        if (res.code) {
          const outboundOrderId = res.data.id || dialogFormData.value.id
          // 构造明细数据
          const detailsData = []
          selectedItems.value.forEach(item => {
            // 检查是否有仓库分配数据，如果没有则使用默认值
            const allocations = warehouseAllocation.value[item.skuId] || [
              {
                warehouseId: 0,
                areaId: 0,
                locaId: 0,
                quantity: item.count
              }
            ]
            // 如果有仓库分配数据，则按分配数据构造明细
            allocations.forEach(alloc => {
              detailsData.push({
                // 使用实体类字段名
                skuId: item.skuId,
                outCount: alloc.quantity || item.count,
                targetWarehouseId: alloc.warehouseId || 0,
                targetWarehouseAreaId: alloc.areaId || 0,
                targetWarehouseAreaLocaId: alloc.locaId || 0,
                outboundOrderId: outboundOrderId,
                pickStatus: 1, // 默认未拣货
                saasId: dialogFormData.value.saasId || '',
                isDel: 1
              })
            })
          })
          // 批量保存明细数据
          if (detailsData.length > 0) {
            await batchSaveApi(detailsData)
          }
          ElMessage.success('操作成功！')
          resetForm()
          emit('refresh')
        } else {
          ElMessage.error('保存失败！')
        }
      } catch (error) {
        console.error(error)
        ElMessage.error('操作异常！')
      }
    }
  })
}


const onItemConfirm = (items) => {
  items.forEach(item => addItem(item))
  showItemSelect.value = false
  calculateTotals() // 确保添加商品后更新总计
}

const onItemCancel = () => {
  showItemSelect.value = false
}

defineExpose({
  dialogFormData,
  dialogVisible,
  handleEdit: (row) => {
    dialogFormData.value = { ...row }
    dialogVisible.value = true
  }
})
</script>

<template>
  <el-dialog v-model="dialogVisible" title="发货管理" width="1000px">
    <el-form :model="dialogFormData" label-width="120px" ref="ruleFormRef" :rules="rules">
      <el-form-item label="客户名称" prop="customerId">
        <el-select v-model="dialogFormData.customerId" placeholder="请选择客户">
          <el-option v-for="item in customerList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <!-- 商品信息区域 -->
      <el-form-item label="商品信息" v-if="selectedItems.length > 0">
        <div v-for="(item, index) in selectedItems" :key="index" class="item-group">
          <div style="display: flex; gap: 10px; margin-bottom: 10px;">
            <!-- 商品名称 -->
            <el-input v-model="item.title" placeholder="商品名称" style="width: 150px;" />

            <!-- 商品编码 -->
            <el-input v-model="item.code" placeholder="商品编码" style="width: 150px;" />

            <!-- 规格编码 -->
            <el-input v-model="item.commodityCode" placeholder="规格编码" style="width: 150px;" />

            <!-- 数量 -->
            <el-input-number v-model="item.count" :min="1" style="width: 150px;" @change="changeCount(index, $event)"
              placeholder="数量" />

            <!-- 删除按钮 -->
            <el-button type="danger" size="small" @click="removeItem(index)">删除</el-button>
          </div>
        </div>
      </el-form-item>

      <!-- 添加商品按钮 -->
      <el-form-item>
        <el-button @click="showItemSelect = true" type="primary" style="float: right">+</el-button>
      </el-form-item>

      <!-- 商品选择弹窗 -->
      <item-select-dialog v-if="showItemSelect" v-model="showItemSelect" @confirm="onItemConfirm"
        @cancel="onItemCancel" />
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="confirm">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.item-group {
  border: 1px solid #ebeef5;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
}
</style>
<style scoped>
.item-group {
  border: 1px solid #ebeef5;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
}

.el-form-item__label {
  font-size: 12px;
  color: #606266;
  margin-bottom: 4px;
}
</style>